﻿using System;
using System.IO;
using System.Threading.Tasks;
using System.Web;
using Newtonsoft.Json;
using Tisonet.Dobrak.Domain.Models;
using Tisonet.Dobrak.Domain.Services.Downloaders;

namespace Tisonet.Dobrak.Domain.Services.Movies
{
    public class CsfdApiMovieProvider : IMoviesProvider
    {
        private const string CSFD_API_WEB_URL = "http://csfdapi.cz";

        private readonly IDownloader _downloader;

        public CsfdApiMovieProvider(IDownloader downloader)
        {
            _downloader = downloader;
        }

        public async Task<Movie> GetMovieAsync(string movieName)
        {
            Uri sourceWebUri = CreateSourceUri(movieName);

            Stream stream = await _downloader.DownloadAsync(sourceWebUri);

            using (var streamReader = new StreamReader(stream))
            {
                using (var jsonReader = new JsonTextReader(streamReader))
                {
                    var serializer = new JsonSerializer();
                    var csfdMovie = serializer.Deserialize<CsfdMovie[]>(jsonReader);

                    if (csfdMovie != null && csfdMovie.Length > 0)
                    {
                        Movie movie = new Movie();

                        movie.Name = csfdMovie[0].names["cs"];
                        movie.Runtime = csfdMovie[0].runtime;
                        movie.Year = csfdMovie[0].year.ToString();

                        return movie;
                    }
                   
                }
            }

            return null;
        }

        private Uri CreateSourceUri(string movieName)
        {
            return new Uri(string.Format("{0}/movie?search={1}", CSFD_API_WEB_URL, HttpUtility.UrlEncode(movieName)));
        }
    }
}
